package com.weichai.app.page.home.view;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.baidu.aip.asrwakeup3.core.recog.MyRecognizer;
import com.baidu.aip.asrwakeup3.core.recog.listener.ChainRecogListener;
import com.baidu.aip.asrwakeup3.core.recog.listener.IRecogListener;
import com.baidu.aip.asrwakeup3.core.recog.listener.MessageStatusRecogListener;
import com.baidu.speech.EventManager;
import com.google.gson.Gson;
import com.scwang.smart.refresh.footer.ClassicsFooter;
import com.scwang.smart.refresh.header.ClassicsHeader;
import com.weichai.app.R;
import com.weichai.app.arch.base.BaseFragment;
import com.weichai.app.arch.config.RouterParams;
import com.weichai.app.arch.utils.GpsUtil;
import com.weichai.app.arch.utils.NetworkUtil;
import com.weichai.app.arch.utils.StringUtil;
import com.weichai.app.bean.AdvEntity;
import com.weichai.app.bean.EntranceEntity;
import com.weichai.app.bean.HomeEntity;
import com.weichai.app.bean.InformationEntity;
import com.weichai.app.bean.MaintenanceOrderEntity;
import com.weichai.app.databinding.FragmentHomeBinding;
import com.weichai.app.page.home.adapter.HomeAdapter;
import com.weichai.app.page.home.dialog.CancelConfirmPopup;
import com.weichai.app.page.home.dialog.ScanResultPopup;
import com.weichai.app.page.home.viewmodel.HomeVM;
import com.weichai.app.page.main.MainModel;
import com.weichai.app.views.speech.BaiduASRDigitalDialog;
import com.weichai.app.views.speech.DigitalDialogInput;
import com.yzq.zxinglibrary.android.CaptureActivity;
import com.yzq.zxinglibrary.common.Constant;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.jzvd.Jzvd;
import dev.utils.app.AppUtils;
import dev.utils.app.IntentUtils;
import dev.utils.app.ResourceUtils;
import dev.utils.app.ScreenUtils;
import dev.utils.app.SizeUtils;
import dev.utils.app.permission.PermissionUtils;
import dev.utils.app.toast.ToastUtils;

/**
 * @ClassName: HomeFragment
 * @Description:
 * @Author: 祖安
 * @Date: 2021/9/1 4:52 下午
 */
public class HomeFragment extends BaseFragment<FragmentHomeBinding, HomeVM> {
    private static final int REQUEST_CODE_SCAN = 100;
    private static final int REQUEST_CODE_SPEECH = 200;
    private EventManager asr;
    private boolean enableOffline;
    private Gson gson;
    private HomeAdapter homeAdapter;
    private int totalScrollY;
    private ChainRecogListener chainRecogListener;
    private MyRecognizer myRecognizer;
    private boolean running;
    private DigitalDialogInput input;
    private GpsUtil gpsUtil;

    @Override
    public void onDestroyView() {
        if (null != gpsUtil) {
            gpsUtil.onDestroy();
        }
        super.onDestroyView();
    }

    @Override
    protected void initView() {
        gpsUtil = new GpsUtil(mActivity);
        gpsUtil.setGPSInterface(new GpsUtil.GPSInterface() {
            @Override
            public void gpsSwitchState(boolean gpsOpen) {
                if (gpsOpen) {
                    mViewBinding.rlLocationOff.setVisibility(View.GONE);
                } else {
                    mViewBinding.rlLocationOff.setVisibility(View.VISIBLE);
                }
            }
        });
        if (!GpsUtil.gpsIsOpen(mActivity)) {
            mViewBinding.rlLocationOff.setVisibility(View.VISIBLE);
        }
        mViewBinding.tvOpen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setAction(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                AppUtils.startActivity(intent);
            }
        });
        mViewBinding.ivClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mViewBinding.rlLocationOff.setVisibility(View.GONE);
            }
        });
        setMaxEms(getViewModelOfActivity(MainModel.class).locationCity.getValue());
        getViewModelOfApp(MainModel.class).entranceList.observe(this, new Observer<List<EntranceEntity>>() {
            @Override
            public void onChanged(List<EntranceEntity> entranceEntityList) {
                List<EntranceEntity> entranceEntities = mViewModel.entranceList.getValue();
                if (null != entranceEntities) {
                    entranceEntities.clear();
                    entranceEntities.add(new EntranceEntity(R.mipmap.ic_customer_service_phone, "客服电话"));
                    entranceEntities.addAll(entranceEntityList);
                    entranceEntities.add(new EntranceEntity(R.mipmap.ic_more, "更多"));
                }
                mViewModel.entranceList.setValue(entranceEntities);
            }
        });
        getViewModelOfActivity(MainModel.class).selectCity.observe(mActivity, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                setMaxEms(s);
            }
        });

        getViewModelOfActivity(MainModel.class).locationCity.observe(mActivity, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                setMaxEms(s);
            }
        });

        homeAdapter = new HomeAdapter(mActivity);
        mViewBinding.rvHome.setLayoutManager(new LinearLayoutManager(getActivity()));
        mViewBinding.rvHome.setAdapter(homeAdapter);
        List<HomeEntity> homeEntityList = new ArrayList<>();
        homeEntityList.add(new HomeEntity());
        homeEntityList.add(new HomeEntity());
        homeEntityList.add(new HomeEntity());
        homeEntityList.add(new HomeEntity());
        homeEntityList.add(new HomeEntity());
        homeAdapter.setList(homeEntityList);

        homeAdapter.setOnBannerListener(new HomeAdapter.OnBannerClickListener() {
            @Override
            public void onBannerClick(AdvEntity advEntity) {
                Bundle bundle = new Bundle();
                bundle.putString("url", advEntity.pictureInterlinkage);
                navigate(new RouterParams(R.id.web_page, bundle));
            }
        });

        homeAdapter.setOnNewsMoreClickListener(new HomeAdapter.OnNewsMoreClickListener() {
            @Override
            public void onNewsMoreClick() {
                navigate(new RouterParams(R.id.newsFragment));
            }
        });

        homeAdapter.setOnEntranceItemClickListener(new HomeAdapter.OnEntranceItemClickListener() {
            @Override
            public void onEntranceItemClick(EntranceEntity entranceEntity) {
                switch (entranceEntity.functionName) {
                    case "更多":
                        if (StringUtil.isLogin()) {
                            if (!NetworkUtil.isNetworkConnected(mActivity)) {
                                ToastUtils.showToast("网络异常！", Toast.LENGTH_SHORT);
                            }
                            navigate(new RouterParams(R.id.editApplicationFragment));
                        }
                        break;
                    case "客服电话":
                        if (TextUtils.isEmpty(mViewModel.phoneNumber.getValue())) {
                            ToastUtils.showToast("客服电话为空！", Toast.LENGTH_SHORT);
                            return;
                        }

                        CancelConfirmPopup cancelConfirmPopup = new CancelConfirmPopup(mActivity);
                        cancelConfirmPopup.showAlert(new CancelConfirmPopup.AlertHint(mViewModel.phoneNumber.getValue(),
                                "取消", "拨打", new CancelConfirmPopup.OnConfirmListener() {
                            @Override
                            public void onConfirm() {
                                StringUtil.callPhone(mViewModel.phoneNumber.getValue());
                            }

                            @Override
                            public void onCancel() {

                            }
                        }));
                        break;
                    case "故障码查询":
                        if (StringUtil.isLogin()) {
                            if (!NetworkUtil.isNetworkConnected(mActivity)) {
                                ToastUtils.showToast("网络异常！", Toast.LENGTH_SHORT);
                            }
                            navigate(new RouterParams(R.id.faultCodeFragment));
                        }
                        break;
                    case "服务站":
                        if (StringUtil.isLogin()) {
                            navigate(new RouterParams(R.id.serviceStationFragment));
                        }
                        break;
                    case "潍柴商城":
                        if (!NetworkUtil.isNetworkConnected(mActivity)) {
                            ToastUtils.showToast("网络异常！", Toast.LENGTH_SHORT);
                        }
                        getViewModelOfActivity(MainModel.class).currentItem.setValue(1);
                        break;
                    case "立即维修":
                        navigate(new RouterParams(R.id.repair_imediately));
                        break;
                    case "发动机":
                        navigate(new RouterParams(R.id.mine_engine));
                        break;
                    default:
                        ToastUtils.showToast("功能暂未实现！", Toast.LENGTH_SHORT);
                        break;
                }
            }
        });

        homeAdapter.setOnInfoItemClickListener(new HomeAdapter.OnInfoItemClickListener() {
            @Override
            public void onInfoItemClick(InformationEntity.ListBean listBean) {
                Bundle bundle = new Bundle();
                bundle.putParcelable("listBean", listBean);
                navigate(new RouterParams(R.id.infoDetailsFragment, bundle));
            }
        });

        homeAdapter.setOnInfoItemChildClickListener(new HomeAdapter.OnInfoItemChildClickListener() {
            @Override
            public void onInfoItemChildClick(InformationEntity.ListBean listBean, int position) {
                if (listBean.like == 1) {
                    mViewModel.likesRecordModify(listBean.newsCode, position);
                } else {
                    mViewModel.likesRecordAdd(listBean.newsCode, position);
                }
            }
        });

        homeAdapter.setOnInfoMoreClickListener(new HomeAdapter.OnInfoMoreClickListener() {
            @Override
            public void onInfoMoreClick() {
                navigate(new RouterParams(R.id.information_list_page));
            }
        });

        mViewModel.advEntityList.observe(mActivity, advEntityList -> {
            HomeEntity homeEntity = new HomeEntity();
            homeEntity.advEntityList = advEntityList;
            homeEntityList.set(0, homeEntity);
            homeAdapter.setList(homeEntityList);
        });

        mViewBinding.llTitleBar.setPadding(SizeUtils.dipConvertPx(16),
                mViewBinding.llTitleBar.getTop() + ScreenUtils.getStatusBarHeight() +
                        SizeUtils.dipConvertPx(4),
                SizeUtils.dipConvertPx(16), SizeUtils.dipConvertPx(4));

        mViewBinding.rvHome.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                totalScrollY += dy;
                if (totalScrollY > SizeUtils.dipConvertPx(281)) {
                    setColor(ResourceUtils.getColor(R.color.white), R.color.color_D9000000);
                } else {
                    setColor(0, R.color.white);
                }
            }
        });

        mViewModel.informationEntityList.observe(this, new Observer<List<InformationEntity.ListBean>>() {
            @Override
            public void onChanged(List<InformationEntity.ListBean> listBeans) {
                HomeEntity homeEntity = new HomeEntity();
                homeEntity.listBeanList = listBeans;
                homeEntityList.set(4, homeEntity);
                homeAdapter.setList(homeEntityList);
            }
        });

        mViewModel.entranceList.observe(this, new Observer<List<EntranceEntity>>() {
            @Override
            public void onChanged(List<EntranceEntity> entranceEntityList) {
                HomeEntity homeEntity = new HomeEntity();
                homeEntity.entranceList = entranceEntityList;
                homeEntityList.set(1, homeEntity);
                homeAdapter.setList(homeEntityList);
            }
        });

        mViewModel.maintenanceOrderEntity.observe(this, new Observer<MaintenanceOrderEntity>() {
            @Override
            public void onChanged(MaintenanceOrderEntity maintenanceOrderEntity) {
                List<String> list = new ArrayList<>();
                list.add("派工接收");
                list.add("维修出发");
                list.add("到达");
                list.add("维修完工");
                list.add("服务评价");
                HomeEntity homeEntity = new HomeEntity();
                homeEntity.maintenanceOrderEntity = maintenanceOrderEntity;
                homeEntity.progressLiveData = list;
                homeEntityList.set(3, homeEntity);
                homeAdapter.setList(homeEntityList);
            }
        });

        getViewModelOfApp(MainModel.class).clickLike.observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean clickLike) {
                HomeEntity homeEntity = new HomeEntity();
                homeEntity.listBeanList = mViewModel.informationEntityList.getValue();
                homeEntityList.set(4, homeEntity);
                homeAdapter.setList(homeEntityList);
                if (null != mViewModel.loadMoreEnd.getValue() && mViewModel.loadMoreEnd.getValue()) {
                    mViewBinding.refreshLayout.setEnableLoadMore(false);
                    if (!homeAdapter.hasFooterLayout()) {
                        homeAdapter.addFooterView(getFooterView(), 0);
                    }
                }
            }
        });

        mViewModel.refresh.observe(this, refresh -> mViewBinding.refreshLayout.finishRefresh());
        mViewModel.loadMore.observe(this, loadMore -> mViewBinding.refreshLayout.finishLoadMore());

        mViewModel.loadMoreEnd.observe(this, new Observer<Boolean>() {
            @Override
            public void onChanged(Boolean aBoolean) {
                mViewBinding.refreshLayout.setEnableLoadMore(false);
                if (!homeAdapter.hasFooterLayout()) {
                    homeAdapter.addFooterView(getFooterView(), 0);
                }
            }
        });

        mViewBinding.refreshLayout.setRefreshHeader(new ClassicsHeader(mActivity));
        mViewBinding.refreshLayout.setRefreshFooter(new ClassicsFooter(mActivity));
        mViewBinding.refreshLayout.setOnRefreshListener(refreshlayout -> {
            mViewModel.getList(true);
            refreshlayout.setEnableLoadMore(true);
            if (homeAdapter.hasFooterLayout()) {
                homeAdapter.removeAllFooterView();
            }
        });
        mViewBinding.refreshLayout.setOnLoadMoreListener(refreshlayout -> mViewModel.getList(false));

        chainRecogListener = new ChainRecogListener();
        // DigitalDialogInput 输入 ，MessageStatusRecogListener可替换为用户自己业务逻辑的listener
        chainRecogListener.addListener(new MessageStatusRecogListener(null));
        IRecogListener listener = new MessageStatusRecogListener(null);
        // DEMO集成步骤 1.1 1.3 初始化：new一个IRecogListener示例 & new 一个 MyRecognizer 示例,并注册输出事件
        myRecognizer = new MyRecognizer(mActivity, listener);
        myRecognizer.setEventListener(chainRecogListener); // 替换掉原来的listener

        mViewBinding.ivSpeechInput.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!PermissionUtils.isGranted(Manifest.permission.RECORD_AUDIO)) {
                    if (PermissionUtils.shouldShowRequestPermissionRationale(mActivity,
                            Manifest.permission.RECORD_AUDIO)) {
                        getViewModelOfActivity(MainModel.class).recordAudioPermission.setValue(true);
                    } else {
                        showDialog();
                    }
                } else {
                    start();
                }
            }
        });

        mViewBinding.llCity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!PermissionUtils.isGranted(Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.ACCESS_COARSE_LOCATION)) {
                    if (PermissionUtils.shouldShowRequestPermissionRationale(mActivity,
                            Manifest.permission.ACCESS_FINE_LOCATION,
                            Manifest.permission.ACCESS_COARSE_LOCATION)) {
                        getViewModelOfActivity(MainModel.class).locationPermission.setValue(true);
                    } else {
                        showDialog();
                    }
                } else {
                    navigate(new RouterParams(R.id.citySelectFragment));
                }
            }
        });

        mViewBinding.ivScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!PermissionUtils.isGranted(Manifest.permission.CAMERA,
                        Manifest.permission.READ_EXTERNAL_STORAGE)) {
                    if (PermissionUtils.shouldShowRequestPermissionRationale(mActivity,
                            Manifest.permission.CAMERA,
                            Manifest.permission.READ_EXTERNAL_STORAGE)) {
                        PermissionUtils.permission(Manifest.permission.CAMERA,
                                Manifest.permission.READ_EXTERNAL_STORAGE)
                                .callback(new PermissionUtils.PermissionCallback() {
                                    @Override
                                    public void onGranted() {
                                        Intent intent = new Intent(mActivity, CaptureActivity.class);
                                        startActivityForResult(intent, REQUEST_CODE_SCAN);
                                    }

                                    @Override
                                    public void onDenied(List<String> grantedList, List<String> deniedList,
                                                         List<String> notFoundList) {

                                    }
                                }).request(mActivity);
                    } else {
                        showDialog();
                    }
                } else {
                    Intent intent = new Intent(mActivity, CaptureActivity.class);
                    startActivityForResult(intent, REQUEST_CODE_SCAN);
                }
            }
        });

        mViewModel.motorState.observe(this, motorState -> {
            switch (motorState) {
                // 非潍柴产品
                case 3:
                    com.weichai.app.page.common.dialog.AlertDialog alertDialog = new com.weichai.app.page.common.dialog.AlertDialog(mActivity);
                    alertDialog.showAlert(new com.weichai.app.page.common.dialog.AlertDialog.AlertHint("非潍柴产品",
                            true, new com.weichai.app.page.common.dialog.AlertDialog.OnConfirmListener() {
                        @Override
                        public void onConfirm() {
                            alertDialog.dismiss();
                        }

                        @Override
                        public void onCancel() {

                        }
                    }));
                    break;
                // 添加发动机
                case 4:
                    navigate(new RouterParams(R.id.addEngineFragment));
                    break;
                default:
                    ScanResultPopup scanResultPopup = new ScanResultPopup(mActivity);
                    scanResultPopup.setOnClickListener(new ScanResultPopup.OnClickListener() {
                        @Override
                        public void click(View v) {
                            switch (v.getId()) {
                                case R.id.iv_close:
                                    scanResultPopup.dismiss();
                                    break;
                                case R.id.tv_repair_immediately:
                                    break;
                                case R.id.tv_appointment_maintenance:
                                    break;
                                case R.id.tv_edit_engine:
                                    break;
                                default:
                                    break;
                            }
                        }
                    });
                    break;
            }
        });
    }

    private View getFooterView() {
        return getLayoutInflater().inflate(R.layout.footer_view, mViewBinding.rvHome, false);
    }

    private void setMaxEms(String s) {
        if (!TextUtils.isEmpty(s)) {
            if (s.length() > 3) {
                mViewBinding.tvLocation.setText(String.format("%s...", s.substring(0, 3)));
            } else {
                mViewBinding.tvLocation.setText(s);
            }
        }
    }

    /**
     * 刷新
     */
    private void refresh() {
        mViewModel.getAdvList();
        mViewModel.getEntranceList();
        mViewModel.getProgressListData();
        mViewModel.getList(true);
        mViewModel.getPhoneNumber();
        mViewModel.queryEffective();
    }

    @Override
    public void onPause() {
        super.onPause();
        Jzvd.releaseAllVideos();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == REQUEST_CODE_SCAN) {
                if (null != data) {
                    String content = data.getStringExtra(Constant.CODED_CONTENT);
                    mViewModel.motorByState(content);
                }
            } else if (requestCode == REQUEST_CODE_SPEECH) {
                if (null != data) {
                    ArrayList<String> results = data.getStringArrayListExtra("results");
                    if (results != null && results.size() > 0) {
                        String result = (String) results.get(0);
                        Bundle bundle = new Bundle();
                        bundle.putString("searchContent", result.substring(0, result.length() - 1));
                        navigate(new RouterParams(R.id.search_page, bundle));
                    }
                }
            }
        }
    }

    private void showDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
        builder.setMessage("勾选了禁止后不再提示，需要前往应用设置界面开启权限！").setCancelable(false).setPositiveButton("确定", (dialog, which) -> {
            dialog.dismiss();
            AppUtils.startActivity(IntentUtils.getLaunchAppDetailsSettingsIntent());
        }).setNegativeButton("取消", (dialog, which) -> dialog.dismiss());
        AlertDialog alertDialog = builder.create();
        alertDialog.show();
    }

    /**
     * 基于SDK集成2.2 发送开始事件
     * 点击开始按钮
     * 测试参数填在这里
     */
    private void start() {
        // BaiduASRDigitalDialog的输入参数
        input = new DigitalDialogInput(myRecognizer, chainRecogListener, new HashMap<>());
        BaiduASRDigitalDialog.setInput(input); // 传递input信息，在BaiduASRDialog中读取,
        Intent intent = new Intent(mActivity, BaiduASRDigitalDialog.class);
        running = true;
        startActivityForResult(intent, REQUEST_CODE_SPEECH);
    }

    private void setColor(int color, int p) {
        mViewBinding.llTitleBar.setBackgroundColor(color);
        mViewBinding.tvLocation.setTextColor(ResourceUtils.getColor(p));
        mViewBinding.ivArrow.setColorFilter(ResourceUtils.getColor(p));
        mViewBinding.ivSpeechInput.setColorFilter(ResourceUtils.getColor(p));
        mViewBinding.ivScan.setColorFilter(ResourceUtils.getColor(p));
    }

    @Override
    protected void initData() {
        mViewModel.getAdvList();
        mViewModel.getEntranceList();
        mViewModel.getProgressListData();
        mViewModel.getList(true);
        mViewModel.getPhoneNumber();
        mViewModel.queryEffective();
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_home;
    }
}
